<template>
  <!-- 调拨基础信息 -->
  <div class="white-container">
    <el-form :model="supplierForm" :rules="rules" ref="formRef" class="grid-container" label-width="120px">
      <h2 class="section-header">基础信息</h2>
      <el-form :model="purform" :rules="rules" ref="purref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
          <el-row>
              <el-col :span="11">
                  <el-form-item label="调拨单号" prop="al_code">
                      <el-input placeholder="自动获取编号" style="width: 300px;" v-model="purform.al_code" disabled></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="11">
                  <el-form-item label="调拨类型" prop="al_type">
                      <el-select placeholder="请选择" v-model="purform.al_type" style="width:300px">
                          <el-option 
                          v-for="item in Allocationtype"
                          :key="item.bus_id"
                          :value="item.bus_name"
                          :label="item.bus_name">
                          </el-option>
                      </el-select>
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="11">
                  <el-form-item label="调拨申请日" prop="date">
                      <el-date-picker
                          v-model="purform.date"
                          type="datetime"
                          placeholder="请选择"
                          format="YYYY-MM-DD HH:mm:ss"
                          date-format="MMM DD, YYYY"
                          time-format="HH:mm"
                          style="width: 300px;"
                        />
                  </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="调出仓库" prop="out_wh_id">
                  <el-select
                    placeholder="请选择"
                    v-model="purform.out_wh_id"
                    style="width:300px"
                    @change="ShowProduct()"
                    clearable
                  >
                    <!-- 使用 availableOutWarehouses 作为数据源 -->
                    <el-option
                      v-for="item in availableOutWarehouses"
                      :key="item.wh_id"
                      :value="item.wh_id"
                      :label="item.wh_name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="调入仓库" prop="in_wh_id">
                  <el-select
                    placeholder="请选择"
                    v-model="purform.in_wh_id"
                    style="width:300px"
                    @change="ShowProduct()"
                    clearable
                  >
                    <!-- 使用 availableInWarehouses 作为数据源 -->
                    <el-option
                      v-for="item in availableInWarehouses"
                      :key="item.wh_id"
                      :value="item.wh_id"
                      :label="item.wh_name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="经办人" prop="al_user">
                  <el-select placeholder="请选择" v-model="purform.al_user" style="width:300px">
                    <el-option 
                    v-for="item in userdata"
                    :key="item.user_id"
                    :value="item.user_name"
                    :label="item.user_name">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="20">
                  <el-form-item label="备注" prop="remark">
                      <el-input type="textarea" placeholder="请输入" v-model="purform.remark"></el-input>
                  </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </el-form>
  </div>

  <!-- 调拨明细表格区域 -->
  <div class="white-container">
    <!-- 表格标题 -->
    <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">库存调拨</h3>
    <hr style="border:1px solid #ccd0d4;"/>
    
    <!-- 操作按钮 -->
    <div style="text-align: left;margin-left: 20px;">
        <el-button type="success" @click="ShowProduct">添加</el-button>
        <el-button @click="batchRemoveProducts">移除</el-button>
    </div>
  
    <!-- 明细表格 -->
    <el-table 
        :data="selectedProducts" 
        stripe 
        style="margin-top: 10px;"
        @selection-change="SelectChange"
    >
        <!-- 选择列 -->
        <el-table-column type="selection"></el-table-column>
        
        <!-- 序号列 -->
        <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
        
        <!-- 货品信息列 -->
        <el-table-column fixed prop="proc_name" label="货品名称"></el-table-column>
        <el-table-column fixed prop="proc_code" label="货品编号" width="150"></el-table-column>
        <el-table-column prop="proc_model" label="规格型号"></el-table-column>
        <el-table-column prop="proc_primary_unit" label="单位" width="70"></el-table-column>
        <el-table-column prop="type_name" label="货品类型"></el-table-column>
        
        <!-- 库存信息 -->
        <el-table-column label="调出仓库当前库存" width="150">
          <template #default="scope">
            {{ (scope.row.out_wh_stock || 0) - (scope.row.proc_pur_num || 0) }}
          </template>
        </el-table-column>
      
        <el-table-column label="调入仓库当前库存" width="150">
          <template #default="scope">
            {{ (scope.row.in_wh_stock || 0) + (scope.row.proc_pur_num || 0) }}
          </template>
        </el-table-column>
        
        <!-- 调拨数量输入 -->
        <el-table-column prop="proc_pur_num" label="调拨数量" width="150">
            <template #default="scope">
                <el-input-number 
                    v-model="scope.row.proc_pur_num" 
                    :min="1" 
                    :max="scope.row.out_wh_stock"
                    style="width: 120px;"
                />
            </template>
        </el-table-column>
        <el-table-column prop="instock_price" label="入库单价" width="100">
                <template #default="scope">
                    {{ scope.row.instock_price ? Number(scope.row.instock_price).toFixed(2) : '0.00' }}
                  </template> 
              </el-table-column>
            
              <el-table-column prop="ald_total" label="调拨金额" width="100">
                <template #default="scope">
                  {{ ((scope.row.proc_pur_num || 0) * (scope.row.instock_price || 0)).toFixed(2) }}
                </template>
              </el-table-column>
        <el-table-column prop="remark" label="备注" width="150">
            <template #default="scope">
                <el-input v-model="scope.row.remark" placeholder="备注" style="width: 120px;"></el-input>
            </template>
        </el-table-column>
        
        <!-- 操作按钮 -->
        <el-table-column fixed="right" label="操作" width="100">
            <template #default="scope">
                <el-button 
                    type="danger" 
                    size="small" 
                    text="移除" 
                    @click="removeProduct(scope.row.proc_id)"
                >移除</el-button>
            </template>
        </el-table-column>
    </el-table>
  
    <!-- 汇总信息 -->
    <div style="display: flex; justify-content: flex-end; margin-top: 15px; padding-right: 20px;">
        <div style="text-align: right;">
            <span style="margin-right: 20px;">货品种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
            <span style="margin-right: 20px;">调拨数量: <b style="color: red;">{{ calculateTotalQuantity() }}</b></span>
            <span style="margin-right: 20px;">调拨金额: <b style="color: red;">{{ calculateTotalAmount() }}</b></span>
        </div>
    </div>
  </div>
  
  <!-- 添加货品模态框（精简版） -->
  <el-dialog v-model="dialogTableVisible" title="添加货品" width="800">
    <!-- 货品搜索表单 -->
    <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
        <el-form-item label="货品名称" prop="name">
            <el-input v-model="procform.name"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
            <el-select v-model="procform.unit" style="width: 200px;">
                <el-option 
                    v-for="item in units" 
                    :key="item.dict_label" 
                    :label="item.dict_label" 
                    :value="item.dict_label"
                />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
  
    <!-- 货品列表表格 -->
    <el-table 
        :data="procdata" 
        stripe 
        height="400" 
        border 
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
    >
      <!-- 选择列 -->
      <el-table-column  type="selection"  :selectable="(row) => row.out_wh_stock > 0"/>
      <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
      <el-table-column prop="proc_code" label="货品编号"></el-table-column>
      <el-table-column prop="proc_name" label="货品名称"></el-table-column>
      <el-table-column prop="proc_model" label="规格型号"></el-table-column>
      <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
      <el-table-column label="入库单价">
        <template #default="scope">
          {{ scope.row.instock_price ? Number(scope.row.instock_price).toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <!-- 可用库存字段直接使用 product.proc_ky_inventory -->
      <!-- 库存信息 -->
      <el-table-column label="调出仓库当前库存" width="150">
        <template #default="scope">
          {{ scope.row.out_wh_stock }}
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页组件 -->
    <div style="display: flex; justify-content: flex-end; margin-top: 15px;">
        <el-pagination 
            :page-size=10 
            layout="prev, pager, next,jumper" 
            :total="rows"
            v-on:current-change="handlePageChange"
        />
    </div>
  
    <!-- 模态框底部按钮 -->
    <template #footer>
        <div style="text-align: right;">
            <el-button @click="dialogTableVisible = false">取消</el-button>
            <el-button type="success" @click="confirmProductSelection">确定</el-button>
        </div>
    </template>
  </el-dialog>

  <!-- 在上传附件部分添加文件输入 -->
  <div class="white-container">
    <div class="grid-container">
      <h2 class="section-header">上传附件</h2>
      <!-- 文件选择器 -->
      <input 
        type="file" 
        multiple 
        @change="handleFileUpload"
        ref="fileInput"
        style="display: none"
      />
      <div class="upload-section">
        <el-upload
          :file-list="filelist" 
          class="upload-demo"
          action="http://localhost:5194/api/PublicFile/Uploadfile"
          multiple
          name="files"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :limit="3"
          :on-exceed="handleExceed"
          :on-success="handleFileSuccess"
          :headers="headers"
          style="text-align: left;margin-left: 20px;">
          <el-button type="primary">上传附件</el-button>
              <template #tip>
                <span class="upload-tips">
                  您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                </span>
              </template>
      </el-upload>
      </div>
    </div>
  </div>

  <!-- 底部操作栏 -->
  <div class="action-bar">
      <el-button @click="Close">关闭</el-button>
      <el-button @click="OK(1)">保存为草稿</el-button>
      <el-button type="primary" @click="OK(2)">保存</el-button>
  </div>
</template>

<script>
import { useRouter, useRoute } from 'vue-router'
import {ref,reactive,onMounted,computed} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
export default {
  setup(){
    const route = useRoute();
    const router = useRouter();
    //#region 上传附件
      const filelist = ref([])
      //头部带token
      const token=sessionStorage.getItem('token');
      const headers = {
          Authorization: `Bearer ${token}`, // 添加 token 到请求头
      };
      // 上传成功回调方法
      function handleFileSuccess(response, file, fileList) {
          if (Array.isArray(response)) {
              // 创建 { 文件名: URL } 的映射
              const urlMap = response.reduce((map, res) => {
                  if (res.success) map[res.originalName] = res.path;
                  return map;
              }, {});

              // 更新文件列表
              filelist.value = fileList.map(item => ({
                  ...item,
                  url: urlMap[item.name] || item.url,  // 优先使用新URL
                  status: urlMap[item.name] ? 'success' : item.status,
                  originalName: item.originalName || item.name
              }));
          }
      }
      //预览
      function handlePreview(file){
          if (!file.url) {
              ElMessage.error('文件URL不存在，请重新上传');
              return;
          }
          const ext = file.name.split('.').pop().toLowerCase();

          switch (ext) {
              case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                  window.open(file.url, '_blank');
                  break;
              case 'pdf':
                  window.open(file.url, '_blank');
                  break;
              case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                  window.open(file.url, '_blank');
                  break;
              default:
                  // 下载其他格式文件
                  const link = document.createElement('a');
                  link.href = file.url;
                  link.download = file.name;
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
          }
      };

      //移除附件
      function handleRemove(file, fileList) {
          filelist.value = fileList;
      }

      // 查询货品附件
      function GetPurchaseFileByCode(al_code) {
        http.get("/PublicFile/GetPublicFileBy?type=调拨&code=" + al_code)
          .then(res => {
            filelist.value = res.data.map(item => {
              return {
                name: item.title,
                url: item.file_name,
                originalName: item.title
              }
            })
          })
      }
    //#endregion
    //#region 修改
      const warehousedata = ref([]);//仓库数据
      const userdata = ref([]);//用户数据
        const Allocationtype = ref([]);
      
      //查询仓库名
      function GetWarehouses() {
        http.get("/Warehouse/GetWarehouses").then(res => {
          console.log("仓库:", res.data); // 调试用
          warehousedata.value = res.data; // 将查询结果赋值给 Departmentdata
        }).catch(err => {
          console.log(err);
          ElMessage.error('数据加载失败');
        });
      }
      
      //查询用户名
      function GetUser() {
          http.get("/User/GetAllUser").then(res => {
              console.log("用户:", res.data); // 调试用
              userdata.value = res.data; // 将查询结果赋值给 Departmentdata
          }).catch(err => {
              console.log(err);
              ElMessage.error('数据加载失败');
          });
      }
        
      //查询调拨类型
      function GetAllocationtype() {
          http.get("/BusinessType/GetBusinessTypes", {
              params: {
                  field: '调拨'
              }
          }).then(res => {
              console.log("调拨:", res.data); // 调试用
              Allocationtype.value = res.data; // 将查询结果赋值给 Departmentdata
          }).catch(err => {
              console.log(err);
              ElMessage.error('数据加载失败');
          });
      }
      //调拨明细
      // ===== 响应式数据 =====
      const selectedProducts = ref([]); // 已选货品列表
      const procdata = ref([]); // 可选货品列表
      const procform = reactive({ name: "", unit: "" }); // 搜索表单数据
      const dialogTableVisible = ref(false); // 模态框显示状态
      const multipleSelection = ref([]); // 当前选中的货品
      const rows = ref(0); // 总数据量
      const currentPage = ref(1); // 当前页码
      const selectdata = ref([]); // 选中行数据
      const units = ref([]); // 单位字典数据

      // ===== 核心方法 =====
      // 计算单个货品金额
      function calculateAmount(row) {
        // 确保单价和数量为数字，避免字符串拼接错误
        const price = parseFloat(row.proc_pur_price) || 0;
        const quantity = parseInt(row.proc_pur_num) || 0;
        row.proc_pur_total = (price * quantity).toFixed(2); // 保留两位小数
      }

      // 计算总数量
      function calculateTotalQuantity() {
          return selectedProducts.value.reduce((total, p) => total + (p.proc_pur_num || 0), 0);
      }

      // 计算总金额（确保字段存在）
      function calculateTotalAmount() {
        if (selectedProducts.value.length === 0) return '0.00';
        
        const total = selectedProducts.value.reduce((sum, p) => {
          const quantity = parseInt(p.proc_pur_num) || 0;
          const price = parseFloat(p.instock_price) || 0;
          return sum + (quantity * price);
        }, 0);
        
        return total.toFixed(2);
      }

      // 移除单个产品
      function removeProduct(procId) {
          const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
          if (index !== -1) selectedProducts.value.splice(index, 1);
      }

      // 批量移除产品
      function batchRemoveProducts() {
          if(selectdata.value.length === 0) {
              ElMessage.warning('请先选择要移除的货品');
              return;
          }
          
          selectdata.value.forEach(item => {
              const index = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
              if(index !== -1) selectedProducts.value.splice(index, 1);
          });
          
          ElMessage.success(`已移除${selectdata.value.length}个货品`);
      }

      // 获取选中行数据
      function SelectChange(val) {
          selectdata.value = val;
      }
      
      // ===== 模态框相关方法 =====
      // 显示模态框
      function ShowProduct() {
          if (!purform.out_wh_id) {
              ElMessage.warning('未选中调出仓库');
              return;
          }

          // 重置分页和搜索条件
          currentPage.value = 1;
          procform.name = "";
          procform.unit = "";

          // 重新加载货品数据
          All();

          // 显示对话框
          dialogTableVisible.value = true;
      }

      // 重置搜索条件
      function Reset() {
          procform.name = "";
          procform.unit = "";
          All(); // 刷新数据
      }

      // 搜索货品
      function Search() {
          currentPage.value = 1;
          All();
      }

      // 加载货品数据（含分页）
      function All() {
        // 先获取调入仓库的库存数据
        http.get("/Stock/GetStockwhid", {
          params: { wh_id: purform.in_wh_id }
        }).then(inwhResponse => {
          // 创建货品ID到库存量的映射
          const inStockMap = {};
          console.log("调入:", inwhResponse.data);
          inwhResponse.data.forEach(stock => {
            if (!inStockMap[stock.proc_id]) {
              inStockMap[stock.proc_id] = 0;
            }
            inStockMap[stock.proc_id] += stock.stk_hand_num;
          });

          // 然后获取调出仓库的货品数据
          http.get("/Product/GetProductsByIds", {
            params: {
              CurrentPage: currentPage.value,
              wh_id: purform.out_wh_id,
              proc_code: procform.name,
              proc_primary_unit: procform.unit
            }
          }).then(res => {
            rows.value = res.data.rows;
            
            // 处理调出仓库的货品数据
            procdata.value = res.data.list.map(item => {
              // 计算调出仓库库存
              const stocks = item.stocks || [];
              const outStock = stocks.reduce((sum, stock) => sum + stock.stk_hand_num, 0);
              
              // 获取调入仓库库存
              const inStock = inStockMap[item.product.proc_id] || 0;
              
              return {
                ...item.product,
                out_wh_stock: outStock,
                in_wh_stock: inStock
              };
            });
            console.log("货物数据:", procdata.value);
          });
        });
      }

      const id = ref(route.query ? route.query.id || null : null);

      // GetSelectedProducts 方法
      async function GetSelectedProducts() {
        try {
          const res = await http.get(`/Allot_d/GetAllot_d?id=${id.value}`);

          if (res.data?.length) {
            console.log("从表:", res.data);

            // 1. 获取货品ID数组
            const productIds = res.data.map(item => item.proc_id);
            console.log("货品ID列表:", productIds);

            // 2. 安全获取货品详情
            const params = new URLSearchParams();
            productIds.forEach(id => params.append('proc_ids', id));

            const productsRes = await http.get("/Product/GetPIds", { params });
            console.log("货品详情响应:", productsRes.data);

            // 3. 构建货品详情的映射，以 proc_id 为键
            const productMap = {};
            productsRes.data.forEach(p => {
              productMap[p.proc_id] = p;
            });

            // 4. 确保仓库ID已经加载
            console.log("调入仓库ID:", purform.in_wh_id);
            console.log("调出仓库ID:", purform.out_wh_id);
            
            if (!purform.in_wh_id || !purform.out_wh_id) {
              console.warn("仓库ID未加载，等待仓库数据...");
              return;
            }

            // 5. 获取调入仓库库存 - 修正参数名
            const inStockRes = await http.get("/Stock/GetStockwhid", {
              params: { whid: purform.in_wh_id }  // 改为whid
            });
            console.log("调入仓库库存:", inStockRes.data);

            // 6. 获取调出仓库库存 - 修正参数名
            const outStockRes = await http.get("/Stock/GetStockwhid", {
              params: { whid: purform.out_wh_id }  // 改为whid
            });
            console.log("调出仓库库存:", outStockRes.data);

            // 7. 构建库存映射：按 proc_id 累加实际库存量
            const inStockMap = {};
            if (inStockRes.data?.length) {
              inStockRes.data.forEach(stock => {
                if (stock.proc_id && stock.stk_hand_num) {
                  inStockMap[stock.proc_id] = (inStockMap[stock.proc_id] || 0) + stock.stk_hand_num;
                }
              });
            }

            const outStockMap = {};
            if (outStockRes.data?.length) {
              outStockRes.data.forEach(stock => {
                if (stock.proc_id && stock.stk_hand_num) {
                  outStockMap[stock.proc_id] = (outStockMap[stock.proc_id] || 0) + stock.stk_hand_num;
                }
              });
            }

            console.log("调入库存映射:", inStockMap);
            console.log("调出库存映射:", outStockMap);

            // 8. 合并数据并添加库存字段
            selectedProducts.value = res.data.map(detail => {
              const product = productMap[detail.proc_id] || {};

              return {
                proc_id: detail.proc_id,
                proc_name: detail.proc_name || product.proc_name || "未知",
                proc_pur_num: detail.ald_num,
                proc_pur_price: detail.ald_price,
                proc_pur_total: detail.ald_total,
                remark: detail.remark,
                ...product,

                //  添加库存字段
                out_wh_stock: outStockMap[detail.proc_id] || 0,
                in_wh_stock: inStockMap[detail.proc_id] || 0
              };
            });
          }

          console.log("最终库存调拨明细:", selectedProducts.value);
        } catch (error) {
          console.error("获取已添加货品失败:", error);
          ElMessage.error("获取已添加货品失败");
        }
      }


      // 分页切换
      function handlePageChange(val) {
          currentPage.value = val;
          All();
      }

      // 处理货品选择变化
      function handleSelectionChange(selection) {
          multipleSelection.value = selection;
      }
      
      // 行样式设置（库存不足时高亮）
      function tableRowClassName({ row }) {
        if (row.proc_ky_inventory <= 0) {
          return 'warning-row';
        }
        return '';
      }

      // 数量变化时触发金额计算
      function handleQuantityChange(row) {
        if (row.proc_pur_num > row.proc_ky_inventory) {
          row.proc_pur_num = row.proc_ky_inventory;
          ElMessage.warning('调拨数量不能超过可用库存');
        }
        calculateAmount(row); // 关键：数量变化时调用金额计算
      }
      // 确认选择货品
      // 添加货品时初始化调拨单价和总金额
      function confirmProductSelection() {
        if (multipleSelection.value.length === 0) {
          ElMessage.warning('请至少选择一个产品');
          return;
        }
        const invalidItems = multipleSelection.value.filter(
          item => item.proc_ky_inventory <= 0
        );
        if (invalidItems.length > 0) {
          ElMessage.error('请选择库存大于 0 的货品');
          return;
        }
        multipleSelection.value.forEach(item => {
          const existingIndex = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
          if (existingIndex === -1) {
            selectedProducts.value.push({
              ...item,
              proc_pur_num: 1,
              proc_pur_price: item.instock_price || 0, // 初始化调拨单价（使用入库价）
              proc_pur_total: (item.instock_price * 1).toFixed(2) // 初始化调拨总金额
            });
          } else {
            const newQuantity = selectedProducts.value[existingIndex].proc_pur_num + 1;
            if (newQuantity > item.proc_ky_inventory) {
              ElMessage.error(`库存不足，${item.proc_name} 可用库存为 ${item.proc_ky_inventory}`);
              return;
            }
            selectedProducts.value[existingIndex].proc_pur_num = newQuantity;
            calculateAmount(selectedProducts.value[existingIndex]); // 数量变化时重新计算金额
          }
        });
        dialogTableVisible.value = false;
      }
      //end

      const purform = reactive({
        al_code: '',    // 调拨单号
        al_user: '',    // 经办人
        out_wh_id:null, //调出仓库
        in_wh_id:null,  //调入仓库
        al_type:'',     //调拨类型
        date: null,     // 调拨申请日
        remark: ''      // 备注
      });

      // 查询Id查调拨数据
      function GetIdSupplier() {
          return http.get("/Allot_h/GetId", {
              params: {
                  id: id.value
              }
          }).then(async res => {
              const apiData = res.data; 
              console.log("调拨:", apiData);
              Object.assign(purform, {
                  al_code: apiData.al_code,
                  al_user: apiData.al_user,
                  out_wh_id: apiData.out_wh_id,
                  in_wh_id: apiData.in_wh_id,
                  al_type: apiData.al_type,
                  date: apiData.al_date,
                  remark: apiData.remark
              });
              
              console.log("设置后的仓库ID - 调出:", purform.out_wh_id, "调入:", purform.in_wh_id);
              
              // 获取到仓库ID后，重新加载货品数据和已选产品
              if (purform.out_wh_id && purform.in_wh_id) {
                  All(); // 重新加载货品数据
                  await GetSelectedProducts(); // 重新获取已选择的产品
              }
              
              GetPurchaseFileByCode(purform.al_code);
          }).catch(err => {
              console.log(err);
              ElMessage.error('数据加载失败');
          });
      }

      // 在 setup 函数中添加保存方法
      async function OK(alstatus) {
        try {
          // 验证表单必填项
          if (!purform.out_wh_id || !purform.in_wh_id || !purform.al_type) {
            ElMessage.warning('请完善基础信息');
            return;
          }

          // 验证至少选择一个货品
          if (selectedProducts.value.length === 0) {
            ElMessage.warning('请至少选择一个货品');
            return;
          }

          const user = JSON.parse(sessionStorage.getItem("user"));

          // 构造请求数据
          const updateAllotDto = {
            updateAllot_hDto: {
              al_id: id.value,
              al_type: purform.al_type,
              al_date: purform.date ? new Date(purform.date).toISOString() : new Date().toISOString(),
              out_wh_id: purform.out_wh_id,
              out_wh_name: warehousedata.value.find(w => w.wh_id === purform.out_wh_id)?.wh_name || '',
              in_wh_id: purform.in_wh_id,
              in_wh_name: warehousedata.value.find(w => w.wh_id === purform.in_wh_id)?.wh_name || '',
              al_user: purform.al_user,
              al_categories: selectedProducts.value.length,
              al_num: calculateTotalQuantity(),
              al_total: parseFloat(calculateTotalAmount()),
              al_status: alstatus, // 默认状态
              update_name: user.name,
              update_time: new Date(),
              remark: purform.remark
            },
            addAllot_dSDto: selectedProducts.value.map(item => ({
              proc_id: item.proc_id,
              proc_name: item.proc_name,
              ald_num: item.proc_pur_num,
              ald_price: item.instock_price,
              ald_total: parseFloat((item.proc_pur_num * item.instock_price).toFixed(2)),
              remark: item.remark || ''
            }))
          };

          // 发送请求
          const res = await http.post("/Allot_h/UpdateAudit", updateAllotDto);

          if (filelist.value.length > 0) {
            filelist.value.forEach(file => {
              http.post("/PublicFile/AddFile?type=调拨&code=" + purform.al_code + "&file=" + file.url+"&title="+file.originalName)
            });
          }
          
          // 处理响应
          if (res.data > 0) {
              ElMessage.success('修改成功');
              router.back();
          } else {
              ElMessage.error('修改失败，请检查数据');
          }
        } catch (err) {

        }
      }

      const availableOutWarehouses = computed(() => {
        if (!purform.in_wh_id) {
          return warehousedata.value;
        }
        return warehousedata.value.filter(wh => wh.wh_id !== purform.in_wh_id);
      });

      const availableInWarehouses = computed(() => {
        if (!purform.out_wh_id) {
          return warehousedata.value;
        }
        return warehousedata.value.filter(wh => wh.wh_id !== purform.out_wh_id);
      });

      onMounted(async () => {
        try {
          await GetWarehouses(); // 先获取仓库列表
          await GetUser(); // 获取用户列表
          await GetAllocationtype();
          
          if (id.value) {
            await GetIdSupplier(); // 获取调拨单基础信息（包含仓库ID）
            // 确保仓库ID加载完成后再获取产品数据
            setTimeout(async () => {
              await GetSelectedProducts(); // 获取已选择的产品
            }, 100);
          }
        } catch (error) {
          console.error("页面初始化失败:", error);
        }
      });
    //#endregion

    //关闭
    function Close(){
      router.back();
    }

    return {
        //关闭
        Close,
        // 数据
        Allocationtype,
        selectedProducts,
        procdata,
        procform,
        dialogTableVisible,
        rows,
        units,
        selectdata,
        availableOutWarehouses,
        availableInWarehouses,
        
        // 方法
        handleQuantityChange,
        calculateAmount,
        calculateTotalQuantity,
        calculateTotalAmount,
        removeProduct,
        batchRemoveProducts,
        SelectChange,
        ShowProduct,
        Reset,
        Search,
        handlePageChange,
        handleSelectionChange,
        confirmProductSelection,
        tableRowClassName,
        All,
        OK,
      //修改
      userdata,//用户数据
      warehousedata,//仓库数据
      purform,//添加表单
      //end
      //beginning:上传
      filelist,
      token,
      headers,
      handleFileSuccess,
      handlePreview,
      handleRemove,
      GetPurchaseFileByCode
      //end
    };
  }
}
</script>

<style scoped>
:deep(.el-table .warning-row) {
background-color: #fef0f0 !important;
}

:deep(.el-table .warning-row > td .el-checkbox__input .el-checkbox__inner) {
background-color: #f5f7fa;
border-color: #e4e7ed;
cursor: not-allowed;
}

:deep(.el-table .warning-row > td .el-checkbox__input) {
cursor: not-allowed;
}
.white-container {
background: white;
border-radius: 12px;
margin-bottom: 50px;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
width: 70%;
}

.grid-container {
padding: 25px;
}

/* 标题左对齐 */
.section-header {
  grid-column: span 12;
  padding-bottom: 15px;
  margin-bottom: 20px;
  border-bottom: 1px solid #e6e6e6;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  text-align: left; /* 新增 */
}

.section-header {
grid-column: span 12;
padding-bottom: 15px;
margin-bottom: 20px;
border-bottom: 1px solid #e6e6e6;
font-size: 18px;
font-weight: 600;
color: #2c3e50;
}

.upload-section {
grid-column: span 12;
margin-top: 20px;
display: flex;
align-items: center;
gap: 10px;
}

.upload-tips {
color: #666;
margin-top: 5px;
font-size: 13px;
}

/* 保留必要的按钮样式 */
.action-bar {
position: fixed;
bottom: 0;
right: 0.5%;
left: 210px;
background: white;
border-top: 1px solid #e6e6e6;
padding: 15px;
text-align: right;
}

.action-btn {
border: none;
padding: 8px 20px;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
}
</style>
